// pages/upload/index.js
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    progress: 0,
    progressHidden: true,
    userInfo: '',
    fileList: []
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    const userInfo = app.globalData.userInfo
    this.setData({
      userInfo: userInfo
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  },

  /**
   * 选择图片
   */
  uploadTap: function() {
    const me = this;
    if (me.data.userInfo) {
      const fileList = me.data.fileList
      if (fileList.length === 4) {
        wx.showToast({
          title: '一次上传4张很多啦!',
          icon: 'none'
        })
        return false;
      }
      wx.chooseImage({
        count: 4,
        success: function(res) {
          const tempFilePaths = res.tempFilePaths
          let fileList = me.data.fileList
          if (Array.isArray(tempFilePaths)) {
            fileList = fileList.concat(tempFilePaths)
          } else {
            fileList.push(tempFilePaths)
          }
          me.setData({
            fileList: fileList
          })
        },
      })
    }
  },
  cancelChoice(e) { //删除图片
    const idx = e.target.dataset.idx
    let fileList = this.data.fileList
    fileList.splice(idx, 1)
    this.setData({
      fileList: fileList
    })
  },
  uploadCheck() { //确认上传
    const me = this;
    const fileList = this.data.fileList
    const fileLen = fileList.length
    if (fileLen === 0) {
      wx.showToast({
        title: '请先选择图片',
        icon: 'none'
      })
    } else {
      me.loopUploadFile(0)
    }
  },
  loopUploadFile(index) { //循环上传图片
    const me = this;
    const fileList = this.data.fileList
    const fileLen = fileList.length
    const file = fileList[index]
    me.uploadFileHandle(file, index).then(function(res) {
      console.log('uploadFileHandleRes', res)
      if (Number(index) + 1 < fileLen) {
        return me.loopUploadFile(Number(index) + 1)
      } else {
        me.setData({
          fileList: []
        })
        wx.showToast({
          title: '上传完成'
        })
      }
    }).catch((res) => {
      wx.showToast({
        title: '上传失败',
        icon: 'none'
      })
    })
  },
  uploadFileHandle(file, index) { //上传图片
    const me = this;
    const currentImg = Number(index) + 1
    return new Promise((resolve, reject) => {
      me.setData({
        progressHidden: false
      })
      wx.showLoading({
        title: '正在上传第' + currentImg + '张图片',
        mask: true
      })
      const uploadTask = wx.uploadFile({
        url: app.globalData.host + 'img/upload',
        filePath: file,
        name: 'img',
        formData: {
          open_id: app.globalData.openId
        },
        success(res) {
          const data = JSON.parse(res.data)
          if (data.state === 'success') {
            resolve('上传成功')
          } else {
            reject(data.msg)
          }
        },
        fail(res) {
          reject(res)
        },
        complete() {
          me.setData({
            progressHidden: true,
            progress: 0
          })
        }
      })

      uploadTask.onProgressUpdate((res) => {
        me.setData({
          progress: res.progress
        })
      })
    })
  },
  onGotUserInfo(e) {
    const me = this
    if (e.detail.errMsg === 'getUserInfo:ok') {
      wx.showLoading({
        title: '登录中...',
      })
      const userInfo = JSON.parse(e.detail.rawData)
      wx.setStorage({
        key: 'userInfo',
        data: userInfo
      })
      wx.login({
        success(res) {
          const code = res.code
          wx.getUserInfo({
            success(res) {
              const {
                encryptedData,
                iv,
                signature,
                rawData
              } = res
              wx.request({
                url: app.globalData.host + 'user/store',
                method: 'POST',
                data: {
                  code: code,
                  encryptedData: encryptedData,
                  iv: encodeURIComponent(iv)
                },
                success(result) {
                  wx.showToast({
                    title: result.data.msg,
                    icon: result.data.status === 'fail' ? 'none' : 'success'
                  })
                  if (result.data.status === 'success') {
                    me.setData({
                      userInfo: e.detail.userInfo
                    })
                    app.globalData.openId = result.data.data.open_id
                  }
                }
              })
            }
          })
        }
      })
    }
  },
  // socketLink(){
  //   const socketOpen = false
  //   const socketMsgQueue = []
  //   wx.sendSocketMessage({
  //     data: 'tttt',
  //     complete(res) {
  //       console.log(res)
  //     }
  //   })
  //   wx.onSocketOpen(function(res){
  //     console.log('onSocketOpen',res)

  //   })
  //   wx.onSocketError(function(res){
  //     console.log('onSocketError',res)
  //   })
  //   wx.onSocketMessage(function (res) {
  //     console.log(res)
  //   })
  // },
  // closeSocket(){
  //   wx.closeSocket()
  // }
})